with orwith without with orwith without
1 | language documentation Control flow |
1.1 | (Control flow) with orwith without with orwith without |
Documentation for with orwith without with orwith without
assembled from the following types:
language documentation Control flow
From Control flow
(Control flow) with orwith without with orwith without
The with
statement is like if
, but tests for definedness rather than truth, and it topicalizes on the condition, much like given
:
with "abc".index("a") # prints 0
Similarly to elsif
, orwith
may be used to chain definedness tests:
# The below code says "Found a at 0"my = "abc";with .index("a")orwith .index("b")orwith .index("c")else
You may intermix if
-based and with
-based clauses.
# This says "Yes"if 0 orwith Nil orwith 0 ;
As with unless
, you may use without
to check for undefinedness, but you may not add an else
clause:
my = Any;without
There are also with
and without
statement modifiers:
my = (Any, True).roll;say 42 with ;warn "undefined answer" without ;
As with the other chainable constructs, an else
completing a with/if
..orwith/elsif
chain will itself topicalize to the value of the prior (failed) condition's topic (either the topic of with
or the final orwith
or elsif
).
In the case of an else
following a with
or orwith
, topicalizing a value guaranteed to be undefined may seem useless. But it makes for a useful idiom when used in conjunction with operations that may fail, because Failure values are always undefined:
sub may_fail( --> Numeric )with may_fail() ->else
Note that while topicalizing a Failure marks it handled
—so you can use the with
/else
to proceed safely with execution—it doesn't make the Failure value itself safe. Even within the else
clause, if you try to use the value directly, it will result in your else
clause itself failing (or, in Rakudo, "promoting" the Failure into a thrown exception).
But as seen above, you can use the methods of a handled Failure
object the else
topicalizes, such as exception
, if you wish to provide diagnostics or interrogate the underlying Exception.